package com.eleven.mall.service.impl;


import com.eleven.mall.customexception.BusinessException;
import com.eleven.mall.pojo.ExType;
import com.eleven.mall.pojo.GoodsPage;
import com.eleven.mall.mapper.GoodsMapper;
import com.eleven.mall.pojo.entity.Goods;
import com.eleven.mall.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class GoodsServiceImpl implements GoodsService {

    GoodsMapper goodsMapper;

    /**
     * 获取商品列表
     * @param query
     * @param pagenum
     * @param pagesize
     * @return
     */
    @Override
    public GoodsPage getGoodsList(String query, Integer pagenum, Integer pagesize) {
        GoodsPage goodsPage = new GoodsPage();
        PageHelper.startPage(pagenum, pagesize);
        List<Goods> goodsList = goodsMapper.getGoodsList(query);

        PageInfo<Goods> pageInfo = new PageInfo<>(goodsList);
        goodsPage.setTotal((int) pageInfo.getTotal());
        String pageNumS = String.valueOf(pageInfo.getPageNum());
        goodsPage.setPagenum(pageNumS);
        goodsPage.setGoods(goodsList);
        return goodsPage;
    }

    // 根据商品id,删除商品

    @Override
    public Boolean deleteById(Integer id) {
        //检验数据
        if(id<0){
            throw new BusinessException("id 是非法的 "+id, ExType.BussInvalidNum);
        }
        //根据id查找
        Goods good = goodsMapper.selectByPrimaryKey(id);
        //未找到
        if (good == null) {
            throw new BusinessException("id 不存在 "+id,ExType.BussRecordNotFound);
        }
        //找到则进行删除操作
        int delete = goodsMapper.deleteByPrimaryKey(id);
        if (delete == 1) {
            //删除成功
            return true;
        }else {
            //删除失败
            return false;
        }
    }

}
